<!--
  -    Copyright (c) 2018-2025, gewu All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the gewucn.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: gewu
  -->
<template>
  <div class="execution">
    <el-card class="box-card btn-search page-search">
      <div slot="header" class="clearfix">
        <div class="btn-box">
          <el-button
            type="info"
            icon="el-icon-refresh-left"
            @click="refreshChange()"
          ></el-button>
          <el-button
            id="gwButton"
            type="primary"
            style="backgroundcolor: #e1b980"
            icon="el-icon-circle-plus-outline"
            v-if="permissions.ems_emsinsinspectstrategy_add"
            @click="addStrategy"
            >新增</el-button
          >
          <el-button
            type="success"
            icon="el-icon-edit"
            v-if="permissions.ems_emsinsinspectstrategy_edit"
            @click="handleEdit"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-circle-close"
            v-if="permissions.ems_emsinsinspectstrategy_del"
            @click.native="handleDel()"
            >删除</el-button
          >
          <!-- <el-button type="check" icon="el-icon-download" @click="exportExcel"
            >导出</el-button
          > -->
          <el-button
            icon="el-icon-connection"
            style="background-color: #101010; color: white"
            @click="addDevStargry"
            >关联设备</el-button
          >
        </div>
        <div class="icon-box">
          <i class="el-icon-search" @click="searchShow"></i>
          <i class="el-icon-refresh" @click="refreshChange"></i>
          <i class="el-icon-goods"></i>
          <i class="el-icon-setting" @click="columnShow"></i>
          <i class="icon-zuixiaohua" />
        </div>
      </div>
    </el-card>
    <basic-container>
      <el-row :span="24">
        <el-col :xs="24" :sm="24" :md="5" class="user__tree">
          <avue-tree
            :option="treeOption"
            :data="treeData"
            @node-click="nodeClick"
          >
          </avue-tree>
        </el-col>

        <el-col :xs="24" :sm="24" :md="19" class="user__main">
          <!-- <div class="icon-title">
        <img src="/img/ali/yunwei.png" alt />
        <b>{{form.strategyName}} </b>
      </div> -->
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            @row-click="chooseRow"
          >
            <el-table-column prop="deviceNum" label="设备编号">
            </el-table-column>
            <el-table-column prop="deviceName" label="设备名称" width="180">
            </el-table-column>
            <el-table-column prop="brandName" label="品牌"> </el-table-column>
            <el-table-column prop="category" label="类别"> </el-table-column>
          </el-table>
          <div style="text-align: right; margin-top: 20px">
            <el-pagination
              background
              :pager-count="5"
              layout="total,prev, pager, next"
              :page-size="pageSize"
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              :total="total"
            >
            </el-pagination>
          </div>
          <el-dialog
            :title="title"
            :visible.sync="updateAndAdd"
            width="400px"
            append-to-body
          >
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-form-item label="策略名称" prop="strategyName">
                <el-input v-model="form.strategyName" ></el-input>
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="form.remark"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="updateAndAdd = false">取 消</el-button>
              <el-button type="primary" @click="comfireBtn">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
    </basic-container>
    <el-drawer
      class="drawerStyle"
      title="点检项目"
      :show-close="false"
      :visible.sync="detail"
      direction="rtl"
      size="40%"
      append-to-body
      :modal="false"
    >
      <div>
        <div>
          <span class="labelS">设备名称：</span>
          <span class="contentS">{{ detailInfo.deviceName }}</span>
        </div>
        <div>
          <span class="labelS">设备编号：</span>
          <span class="contentS">{{ detailInfo.deviceNum }}</span>
        </div>
        <div>
          <span class="labelS">所属部门：</span>
          <span class="contentS">{{ detailInfo.deptName }}</span>
        </div>
      </div>
      <div class="line"></div>
      <div>
        <el-card shadow="always" class="box-card">
          <div><span class="tableTitle">点检项目</span></div>
          <el-table :data="tableData1" border style="width: 100%">
            <el-table-column prop="itemsName" label="项目"> </el-table-column>
            <el-table-column
              prop="methodBenchmark"
              label="方法及基准"
              width="180"
            >
            </el-table-column>
            <el-table-column label="类型">
              <template slot-scope="scope">
                <span v-if="scope.row.type == 0">文本</span>
                <span v-if="scope.row.type == 1">数值</span>
                <span v-if="scope.row.type == 2">选项</span>
              </template>
            </el-table-column>
            <el-table-column prop="lowerLimit" label="上限"> </el-table-column>
            <el-table-column prop="upperLimit" label="下限"> </el-table-column>
            <el-table-column prop="optional" label="可选项"> </el-table-column>
          </el-table>
          <div style="text-align: right; margin-top: 20px">
            <el-pagination
              background
              :pager-count="5"
              layout="total,prev, pager, next"
              :page-size="spoted.pageSize"
              @current-change="handleCurrentChangespoted"
              :current-page.sync="spoted.currentPage"
              :total="spoted.total"
            >
            </el-pagination>
          </div>
        </el-card>
      </div>
    </el-drawer>
    <el-dialog
      :visible.sync="isRelate"
      width="85%"
      :show-close="false"
      class="relativeDev"
    >
      <DeviceRelate
        @cancel="cancel"
        v-if="isRelate"
        @comfire="comfireAdd"
        :listObj="readyDev"
      ></DeviceRelate>
    </el-dialog>
  </div>
</template>
<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  selectAll,
  selectdevAll,
  getDevAnuth,
  getspot,
} from "@/api/ems/inspection/spot";
import { tableOption } from "@/const/crud/ems/inspection/spot";
import { mapGetters } from "vuex";
import jQuery from "jquery";
import IconTitle from "@/components/icon-title/index.vue";
import DeviceRelate from "../components/deviceRelate";
import { spotAddDev } from "@/api/ems/inspection/dev";
export default {
  name: "spot",
  components: {
    IconTitle,
    DeviceRelate,
  },
  data() {
    return {
      tableData: [],
      treeData: [],
      title: "新增",
      updateAndAdd: false,
      searchForm: {}, // 查询参数
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      spoted: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 5, // 每页显示多少条
      },
      pageSize: 5,
      currentPage: 1,
      total: 0,
      treeOption: {
        nodeKey: "id",
        addBtn: false,
        menu: false,
        props: {
          label: "strategyName",
          value: "id",
        },
      },
      tableLoading: false,
      tableOption: tableOption,
      ids: [],
      selectionList: [],
      detail: false,
      tableData1: [],
      celueId: "",
      width: "70%",
      isRelate: false,
      readyDev: [],
      devObject: {},
      form: {
        strategyName: "",
        remark: "",
      },
      detailInfo: {},
      rules:{
        strategyName: [
            { required: true, message: '请输入策略', trigger: 'blur' }
          ],
      }
    };
  },
  computed: {
    ...mapGetters(["permissions", "theme"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permissions.ems_emsinsinspectstrategy_add,
          false
        ),
        delBtn: this.vaildData(
          this.permissions.ems_emsinsinspectstrategy_del,
          false
        ),
        editBtn: this.vaildData(
          this.permissions.ems_emsinsinspectstrategy_edit,
          false
        ),
      };
    },
  },
  mounted() {
    this.initElement();
    this.changeThme();
    this.getselectAll();
  },
  methods: {
    initElement() {
      var mediumb = document.createElement("b"); //思路一样引入中间元素
      jQuery(".avue-crud__tip").after(mediumb);
      jQuery(".selfTitle").after(jQuery(".avue-crud__tip"));
      jQuery(mediumb).after(jQuery(".selfTitle"));
      jQuery(mediumb).remove();
    },
    selectionChange(list) {
      this.selectionList = list;
      this.single = list.length !== 1;
      this.multiple = !list.length;
      this.ids = list.map((item) => item.id);
    },

    columnShow() {
      this.$refs.crud.$refs.dialogColumn.columnBox = !0;
    },
    // 搜索框显示与否
    searchShow() {
      this.$refs.crud.$refs.headerSearch.searchShow =
        !this.$refs.crud.$refs.headerSearch.searchShow;
    },
    getselectAll() {
      selectAll().then((response) => {
        // console.log(response)
        this.treeData = response.data.data;

        this.celueId = this.treeData[0].id;
        this.selectdevAll();
      });
    },
    nodeClick(data) {
      this.celueId = data.id;
      this.form.strategyName = data.strategyName;
      this.form.remark = data.remark;
      this.selectdevAll();
    },
    selectdevAll() {
      selectdevAll({
        strategyId: this.celueId,
        size: this.pageSize,
        current: this.currentPage,
      }).then((res) => {
        //  console.log(res)
        if (res.data.data) {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        }
      });
    },
    addDevStargry() {
      this.getDevAnuth();
    },
    getDevAnuth() {
      getDevAnuth({ strategyId: this.celueId }).then((res) => {
        
        this.readyDev = res.data.data;
        this.isRelate = true;
        //  this.readyDev = res.data.data;
      });
    },
    handleCurrentChange(index) {
      this.currentPage = index;
      this.selectdevAll();
    },
    handleCurrentChangespoted(index) {
      this.spoted.currentPage = index;
    },
    getspot() {
      getspot({
        id: this.detailInfo.id,
        size: this.spoted.pageSize,
        current: this.spoted.currentPage,
      }).then((res) => {
        this.tableData1 = res.data.data.records;
        this.spoted.total = res.data.data.total;
      });
    },
    chooseRow(row) {
      this.detailInfo = row;
      this.getspot();
      this.detail = true;
    },
    // 列表查询
    getList(page, params) {
      this.tableLoading = true;

      fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
          },
          params,
          this.searchForm
        )
      )
        .then((response) => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    comfireBtn() {
       this.$refs.form.validate((valid) => {
       
          if (valid) {
                   if (this.title == "新增") {
        this.handleSave();
      } else {
        this.handleUpdate();
      }
          } else {
           
      
          }
        });
    
    
    },
    //编辑
    handleEdit() {
      this.title = "修改";
      this.updateAndAdd = true;
    },
    addStrategy() {
      this.title = "新增";
      this.updateAndAdd = true;
      this.form.strategyName = "";
      this.form.remark = "";
    },
    // 删除
    handleDel: function () {
      this.$confirm("是否确认删除所选数据项", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delObj(this.celueId);
        })
        .then((data) => {
          this.$message.success("删除成功");
          this.getselectAll();
          // this.getList(this.page);
        });
    },
    // 更新
    handleUpdate: function () {
      putObj({ ...this.form, id: this.celueId })
        .then((data) => {
          this.$message.success("修改成功");
          // done();
          this.getselectAll();
          this.updateAndAdd = false;
          //   this.getList(this.page);
        })
        .catch(() => {
          // loading();
        });
    },
    // 保存
    handleSave: function () {
      addObj(this.form)
        .then((data) => {
          console.log(data);
          this.$message.success("添加成功");
          // done();
          this.getselectAll();
          this.updateAndAdd = false;
          //   this.getList(this.page);
        })
        .catch(() => {
          // loading();
        });
    },
    // 每页条数改变事件
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    // 当前页发生改变事件
    currentChange(current) {
      this.page.currentPage = current;
    },
    // 查询事件
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      //   this.getList(this.page, form);
      done();
    },
    // 刷新事件
    refreshChange() {
      this.getselectAll();
      //   this.getList(this.page);
    },
    // 导出excel
    exportExcel() {
      this.downBlobFile(
        "/ems/emsinsinspectstrategy/export",
        this.searchForm,
        "emsinsinspectstrategy.xlsx"
      );
    },
    // 改变主题颜色
    changeThme() {
      //"#02b980"
      document.getElementById("gwButton").style.backgroundColor = this.theme;
    },
    cancel() {
      this.isRelate = false;
    },
    comfireAdd(m) {
      spotAddDev({ ...m, id: this.celueId }).then((res) => {
        if (res.data.code == 0) {
          this.$message.success("设备添加成功");
          this.selectdevAll();
          this.isRelate = false;
        } else {
          this.$message.error("设备添加失败");
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/drawer.scss";
::v-deep.relativeDev {
  .el-dialog__header {
    padding: 0;
  }
  .el-dialog__body {
    padding-top: 10px;
  }
}
.icon-title {
  b {
    font-size: 14px;
  }
  .slot {
    font-size: 12px;
    color: #666;
    margin-left: 5px;
  }
  img {
    width: 20px;
    height: 20px;
  }
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
</style>